package model

import (
	"cms/libs"
	"errors"
	"github.com/jinzhu/gorm"
	config "github.com/spf13/viper"
	"math"
	"time"
)

type Apply struct {
	gorm.Model
	CategoryId   uint      `gorm:"column:category_id" json:"category_id" form:"category_id"`
	ShowPosition uint      `gorm:"column:show_position" json:"show_position" form:"show_position"`
	Url          string    `gorm:"column:url" json:"url" form:"url" validate:"required"`
	Title        string    `gorm:"column:title" json:"title" form:"title" validate:"required"`
	Keywords     string    `gorm:"column:keywords" json:"keywords" form:"keywords" validate:"required"`
	Recommend    string    `gorm:"column:recommend" json:"recommend" form:"recommend"`
	Desc         string    `gorm:"column:desc" json:"desc" form:"desc" validate:"required"`
	Status       string    `gorm:"column:status" json:"status" form:"status"`
	Tel          string    `gorm:"column:tel" json:"tel" form:"tel" validate:"required"`
	Image        string    `gorm:"column:image" json:"image" form:"image"`
	VerifyTime   time.Time `gorm:"column:verify_time" json:"verify_time" form:"verify_time"`
}

func (this *Apply) List(page int) ([]Apply, int, int) {
	var data = []Apply{}
	var totalCount int
	db := libs.DB

	limit := config.GetInt("pagination.PageSize")
	offset := (page - 1) * limit
	db.Find(&data).Count(&totalCount)
	db.Offset(offset).Limit(limit).Order("status asc").Find(&data)
	totalPages := int(math.Ceil(float64(totalCount) / float64(limit)))
	return data, totalCount, totalPages
}

func (this *Apply) SearchList(ids []string) []Apply {
	var data = []Apply{}
	db := libs.DB
	db.Where("id in (?)", ids).Order("id desc").Find(&data)
	return data
}

func (this *Apply) Info(id uint) (Apply, error) {
	var apply Apply
	db := libs.DB

	if db.Where("id = ?", id).First(&apply).RecordNotFound() {
		return Apply{}, errors.New("内容未找到")
	}
	return apply, nil
}

func (this *Apply) Add(postValues map[string][]string) error {
	var apply Apply
	db := libs.DB

	if err := libs.FormDecode(&apply, postValues); err != nil {
		return err
	}
	if err := libs.Validate(apply); err != nil {
		return err
	}
	if !db.Where("title = ? ", apply.Title).First(&Apply{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}

	if err := db.Create(&apply).Error; err != nil {
		return err
	}
	return nil
}

func (this *Apply) AddApply(postValues map[string][]string) error {
	var apply Apply
	db := libs.DB

	if err := libs.FormDecode(&apply, postValues); err != nil {
		return err
	}
	if err := libs.Validate(apply); err != nil {
		return err
	}
	if !db.Where("title = ? ", apply.Title).First(&Apply{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}

	apply.Status = "审核中"
	if err := db.Create(&apply).Error; err != nil {
		return err
	}
	return nil
}

func (this *Apply) Update(postValues map[string][]string) error {
	var apply Apply
	db := libs.DB

	if err := libs.FormDecode(&apply, postValues); err != nil {
		return err
	}
	if err := libs.Validate(apply); err != nil {
		return err
	}
	if !db.Where("title = ? and id != ?", apply.Title, apply.ID).First(&Apply{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}
	if db.Where("id = ? ", apply.ID).First(&Apply{}).RecordNotFound() {
		return errors.New("未查询到内容id")
	}

	if apply.Status != "审核中" {
		apply.VerifyTime = time.Now()
	}

	if err := db.Save(&apply).Error; err != nil {
		return err
	}

	if apply.Status == "通过" {
		var nav Nav
		nav.Title = apply.Title
		nav.Url = apply.Url
		nav.Keywords = apply.Keywords
		nav.Desc = apply.Desc
		nav.Image = apply.Image
		nav.From = "申请"
		nav.CategoryId = apply.CategoryId
		nav.ShowPosition = apply.ShowPosition
		nav.Recommend = apply.Recommend
		if err := db.Create(&nav).Error; err != nil {
			return err
		}
	}

	return nil
}

func (this *Apply) Del(id uint) error {
	var apply Apply
	db := libs.DB

	if err := db.Where("id = ?", id).Delete(&apply).Error; err != nil {
		return err
	}
	return nil
}
